package com.yikekong.emq;

import com.yikekong.config.EmqConfig;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * emq 客户端
 */
@Component
@Slf4j
public class EmqClient {

    @Autowired
    private EmqConfig emqConfig;//emq配置

    private MqttClient mqttClient;  //mqtt客户端

    @Autowired
    private EmqMsgProcess emqMsgProcess;

    /**
     * 连接mqtt broker
     */
    public void connect(){
        try {
            mqttClient = new MqttClient(emqConfig.getMqttServerUrl(),"monitor."+ UUID.randomUUID());
            mqttClient.setCallback(emqMsgProcess);
            mqttClient.connect();
        } catch (MqttException e) {
            e.printStackTrace();
            log.error("mqtt 连接异常");
        }
    }


    /**
     * 发布消息
     * @param topic 主题
     * @param msg   消息
     */
    public void publish(String topic,String msg){
        try {
            MqttMessage message = new MqttMessage(msg.getBytes());
            mqttClient.publish(topic,message);  //向某主题发送消息
        } catch (MqttException e) {
            e.printStackTrace();
            log.error("mqtt 发布消息异常");
        }
    }

    /**
     * 订阅主题
     * @param topicName
     */
    public void subscribe(String topicName) throws MqttException {
        mqttClient.subscribe(topicName);
    }

}
